import {
	ref,
	onUnmounted
} from 'vue'
import {
	useToken
} from './useToken' // 导入 useToken

// WebSocket 封装
export function useApiWs(path, params = {}) {
	const data = ref(null)
	const ws = ref(null)
	let currentParams = {
		...params
	} // 保存动态参数

	const {
		getToken
	} = useToken()
	const token = getToken()

	// 构造 ws 完整 URL
	const buildUrl = () => {
		const baseUrl = 'ws://api.flirtyzsex.com'
		const url = new URL(baseUrl + path)

		const allParams = {
			...currentParams
		}
		if (!allParams.token && token) {
			allParams.token = token
		}
		
		Object.entries(allParams).forEach(([k, v]) => {
			if (v !== undefined && v !== null) {
				url.searchParams.append(k, v)
			}
		})

		return url.toString()
	}

	const connect = () => {
		const wsUrl = buildUrl()
		console.log('正在连接 WebSocket 地址:', wsUrl)
		ws.value = new WebSocket(wsUrl)

		ws.value.onopen = () => {
			console.log('✅ WebSocket 连接成功:', path)
			send(currentParams) // 默认发一次
		}
		ws.value.onmessage = (event) => {
			try {
				const msg = JSON.parse(event.data)
				data.value = msg
			} catch (err) {
				console.error('解析消息失败', err)
			}
		}
	}

	const send = (msg) => {
		if (ws.value && ws.value.readyState === WebSocket.OPEN) {
			ws.value.send(JSON.stringify(msg))
		}
	}

	const setParams = (newParams) => {
		currentParams = {
			...currentParams,
			...newParams
		}
	}

	return {
		data,
		connect,
		send,
		setParams
	}
}